(setq ExpandFilePath "d:/workspace/c/my-lib/emacs/")
(defun read-something ()
  (interactive)
  (delete-word)
  (setq abc (read-from-minibuffer "Please Enter Servlet Name:"))
  (insert "import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
")
  (insert (format "public class %s extends HttpServlet" abc))
  (insert "{
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException,IOException
    {
        response.setContentType(\"text/html\");
        PrintWriter out=response.getWriter();
        out.println("");
        out.close();
    }
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException,IOException
    {
        response.setContentType(\"text/html\");
        PrintWriter out=response.getWriter();
        out.println();
        out.close();
    }
}"))

(defun insert-latex-frame ()
  (interactive)
  (delete-word)
  (insert "\\documentclass[a4paper,12pt]{article}
\\begin{document}

\\end{document}"))


(defun insert-init-windows ()
  (interactive)
  (insert "#include <windows.h>

LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ;

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    PSTR szCmdLine, int iCmdShow)
{
     static TCHAR szAppName[] = TEXT (\"HelloWin\") ;
     HWND         hwnd ;
     MSG          msg ;
     WNDCLASS     wndclass ;

     wndclass.style         = CS_HREDRAW | CS_VREDRAW ;
     wndclass.lpfnWndProc   = WndProc ;
     wndclass.cbClsExtra    = 0 ;
     wndclass.cbWndExtra    = 0 ;
     wndclass.hInstance     = hInstance ;
     wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION) ;
     wndclass.hCursor       = LoadCursor (NULL, IDC_ARROW) ;
     wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
     wndclass.lpszMenuName  = NULL ;
     wndclass.lpszClassName = szAppName ;

     if (!RegisterClass (&wndclass))
     {
          MessageBox (NULL, TEXT (\"This program requires Windows NT!\"), 
                      szAppName, MB_ICONERROR) ;
          return 0 ;
     }
     hwnd = CreateWindow (szAppName,                  // window class name
                          TEXT (\"The Hello Program\"), // window caption
                          WS_OVERLAPPEDWINDOW,        // window style
                          CW_USEDEFAULT,              // initial x position
                          CW_USEDEFAULT,              // initial y position
                          CW_USEDEFAULT,              // initial x size
                          CW_USEDEFAULT,              // initial y size
                          NULL,                       // parent window handle
                          NULL,                       // window menu handle
                          hInstance,                  // program instance handle
                          NULL) ;                     // creation parameters
     
     ShowWindow (hwnd, iCmdShow) ;
     UpdateWindow (hwnd) ;
     
     while (GetMessage (&msg, NULL, 0, 0))
     {
          TranslateMessage (&msg) ;
          DispatchMessage (&msg) ;
     }
     return msg.wParam ;
}

LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
     HDC         hdc ;
     PAINTSTRUCT ps ;
     RECT        rect ;
     
     switch (message)
     {
     case WM_CREATE:
          
          return 0 ;

     case WM_PAINT:
          hdc = BeginPaint (hwnd, &ps) ;
          
          
          EndPaint (hwnd, &ps) ;
          return 0 ;
          
     case WM_DESTROY:
          PostQuitMessage (0) ;
          return 0 ;
     }
     return DefWindowProc (hwnd, message, wParam, lParam) ;
}
"))

(global-set-key (kbd "C-x w") 'insert-init-windows)

(defun insert-command ()
  (interactive)
  (insert "heapsort"))

(global-set-key (kbd "C-x c") 'insert-command)

(defun insert-link-command ()
  (interactive)
  (delete-word)
  (setq command (read-from-minibuffer "Enter the programme name:"))
  (insert (format "link kernel32.lib user32.lib gdi32.lib /subsystem:windows /incremental:yes /machine:I386 /out:\"%s.exe\" %s.obj" command command))
)

(defun insert-servlet-xml ()
  (interactive)
  (delete-word)
  (setq servlet-name (read-from-minibuffer "Enter the servlet-name: "))
  (snippet-insert (format "  <servlet>
    <servlet-name>%s</servlet-name>
    <servlet-class>$$%s</servlet-class>
  </servlet>
<servlet-mapping>
  <servlet-name>%s</servlet-name>
  <url-pattern>/%s</url-pattern>
</servlet-mapping>" servlet-name servlet-name servlet-name servlet-name)))


(defun delete-word ()
  (interactive)
  (backward-word 1)
  (setq second-p (point))
  (forward-word 1)
  (setq current-p (point))
  (delete-region current-p second-p))

(defun delete-character()
  (interactive)
  (backward-char 1)
  (setq second-c (point))
  (forward-char 1)
  (setq current-c (point))
  (delete-region current-c second-c))

(defun get-current-word ()
  "Returns the current, or the last entered word."
  (save-excursion
    (backward-word)
    (setq start (point))
    (forward-word)
    (setq end (point))
    (buffer-substring-no-properties start end)))


(defun replace-string-to-mysql ()
  (delete-word)
  (insert "static final String JDBC_DRIVER = \"com.mysql.jdbc.Driver\";
static final String DATABASE_URL = \"jdbc:mysql://localhost/books\";
static final String USERNAME=\"\";
static final String PASSWORD=\"\";"))

(defun replace-string-to-for ()
  (interactive)
  (setq abc (read-from-minibuffer "Please Enter the loop variable"))
  (delete-word)
  (insert (format "for(%s=;%s<= ;%s++){
}" abc abc abc)))

(defun replace-string-to-mysql-getdata ()
  (delete-word)
  (insert "
          Connection connection = null; 
          Statement statement = null; 

          try
          {
             Class.forName( JDBC_DRIVER ); 


             connection =                                                     
                DriverManager.getConnection( DATABASE_URL,USERNAME, PASSWORD );

             statement = connection.createStatement();


             ResultSet resultSet = statement.executeQuery(            
                "" );


             ResultSetMetaData metaData = resultSet.getMetaData();
             int numberOfColumns = metaData.getColumnCount();     
        

             for ( int i = 1; i <= numberOfColumns; i++ ){

                 }

             while ( resultSet.next() )
             {
                for ( int i = 1; i <= numberOfColumns; i++ ){

                    }
             }
          } 
          catch ( SQLException sqlException )
          {
             sqlException.printStackTrace();
             System.exit( 1 );
          } 
          catch ( ClassNotFoundException classNotFound )
          {
             classNotFound.printStackTrace();
             System.exit( 1 );
          } 
          finally 
          {                                                             
             try                                                        
             {                                                          
                statement.close();                                      
                connection.close();                                     
             } 
             catch ( Exception exception )                              
             {                                                          
                exception.printStackTrace();                            
                System.exit( 1 );                                       
             } 
          } 
       }"))

(defun replace-string-to-ajax()
  (interactive)
  (delete-word)
  (insert "function getXMLHTTPRequest() {
  var xmlHttp;
    try
    {
        xmlHttp=new XMLHttpRequest();
    }
    catch(e)
    {
        try
        {
            xmlHttp=new ActiveXObject(\"Msxml2.XMLHTTP\");
        }
        catch (e)
        {
            try
            {
                xmlHttp=new ActiveXObject(\"Microsoft.XMLHTTP\");
            }
            catch(e)
            {
                alert(\"Your browser does not support AJAX!\");
                return false;
            }
        }
    }
return xmlHttp;
}
"))

(defun replace-string-to-pragram ()
  (interactive)
  (setq current-word (get-current-word))
  (cond ((string= current-word "mysqli")
         (replace-string-to-mysql))
        ((string= current-word "servlet")
         (read-something))
        ((string= current-word "java-mysqlconnection")
         (replace-string-to-mysql-getdata))
        ((string= current-word "clx")
         (insert-link-command))
        ((string= current-word "serX")
         (insert-servlet-xml))
        ((string= current-word "ajax")
         (replace-string-to-ajax))
        ((string= current-word "latex")
         (insert-latex-frame))
        ((string= current-word "fori")
         (insert-increase))
        ((string= current-word "ford")
         (insert-descrease))
        ((string= current-word "ant")
         (insert-ant))
        ((string= current-word "antp")
         (insert-antp))
        ((string= current-word "antt")
         (insert-antt))
        ((string= current-word "antc")
         (insert-antc))
        ((string= current-word "c")
         (insert-c-template))
        ((string= current-word "cpp")
         (insert-cpp-template))
        ((string= current-word "createfile")
         (insert-windows-systemprogramming-createfile))
        ((string= current-word "deviceio")
         (insert-windows-systemprogramming-deviceio))
        ((string= current-word "hash")
         (insert-string-hash))
        )
  )

(defun insert-string-hash()
  (interactive)
  (delete-word)
  (insert-file (concat ExpandFilePath "windows-system-programming/stringhash.c"))
  )

(defun insert-windows-systemprogramming-deviceio()
  (interactive)
  (delete-word)
  (insert-file (concat ExpandFilePath "windows-system-programming/DeviceIoControl.c"))
  )

(defun insert-windows-systemprogramming-createfile()
  (interactive)
  (delete-word)
  (insert-file (concat ExpandFilePath "windows-system-programming/createfile.c"))
  )


(defun insert-cpp-template()
  (interactive)
  (delete-word)
  (snippet-insert "#include<iostream>
using namespace std;
int main(int argc, char *argv[])
{
  $.
  return 0;
}
"))

(defun insert-c-template()
  (interactive)
  (delete-word)
  (snippet-insert "#include<stdio.h>
int main(int argc, char *argv[])
{
  $.
  return 0;
}
"))


(defun insert-antc ()
  (interactive)
  (delete-word)
  (snippet-insert "<copy file=\"${src}/$$\" tofile=\"${build}/$$\"/>"))

(defun insert-antp ()
  (interactive)
  (delete-word)
  (snippet-insert "<property name=\"$$\" value=\"$$\"/>"))

(defun insert-antt ()
  (interactive)
  (delete-word)
  (snippet-insert "<target name=\"$$\" depends=\"$$\" description=\"$$\">
    <echo>$$</echo>
    <javac srcdir=\"${src}\" destdir=\"${build}\" includes=\"$$\"/>
  </target>
"))


(global-set-key (kbd "C-8") 'replace-string-to-pragram)

(defun insert-increase ()
  (delete-word)
  (setq element (read-from-minibuffer "Enter the element:"))
  (snippet-insert (format
 "for (%s = $${min}; %s <$${max}; %s++)
    {
      $.
    }" element element element))
  )

(defun insert-descrease ()
  (delete-word)
  (setq element (read-from-minibuffer "Enter the element:"))
  (snippet-insert (format
 "for (%s = $${min}; %s >$${max}; %s--)
    {
      $.
    }" element element element))
  )

(defun insert-ant ()
  (interactive)
  (delete-word)
  (snippet-insert "<?xml version=\"1.0\"?> 
<project name=\"$$\" default=\"$$\" basedir=\".\"> 

     <property name=\"$$\" value=\"$$\"/> 
     <property name=\"build\" value=\"build\"/>
     <!--add the target code here-->
     $$
</project>
"))


(defun frame-title()
  (interactive)
  (setq element (read-from-minibuffer "Enter the titlename:"))
  (setq frame-title-format element)
  )

(defun kill-whole-buffer-imm()
  (interactive)
  (kill-region (point-min) (point-max))
  )

(defun delete-empty-line()
  (interactive)
  (while (re-search-forward "^$" nil t)
    (kill-line)
    ))

  (defun uniquify-all-lines-region (start end)
    "Find duplicate lines in region START to END keeping first occurrence."
    (interactive "*r")
    (save-excursion
      (let ((end (copy-marker end)))
        (while
            (progn
              (goto-char start)
              (re-search-forward "^\\(.*\\)\n\\(\\(.*\n\\)*\\)\\1\n" end t)
              )
          (replace-match "\\1\n\\2")
          )
        )
      )
    )
  
  (defun uniquify-all-lines-buffer ()
    "Delete duplicate lines in buffer and keep first occurrence."
    (interactive "*")
    (uniquify-all-lines-region (point-min) (point-max)))